﻿using EIP.Common.Util;
using MongoDB.Driver;

namespace EIP.Common.MongoDB
{
    /// <summary>
    /// 管理MongoDb连接
    /// </summary>
    public class MongoDbManager
    {
        private MongoDbManager() { }
        private static readonly string ConnectionString = ConfigurationUtil.GetSection("MongoDb:ConnectionString");
        private static IMongoClient _client;
        private static readonly object Locker = new object();
        /// <summary>
        /// 获取MongoDb连接
        /// </summary>
        /// <returns></returns>
        public static IMongoClient CreateDb
        {
            get
            {
                if (_client == null)
                {
                    lock (Locker)
                    {
                        if (_client == null)
                        {
                            _client = GetManager();
                        }
                    }
                }
                return _client;
            }
        }

        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        private static MongoClient GetManager(string connection = null)
        {
            return new MongoClient(connection ?? ConnectionString);
        }
    }
}